package gui.widgets;

import java.awt.Color;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JPanel;

public class CheckboxPanel extends JPanel implements ItemListener {

	private static final long serialVersionUID = 1L;
	private Object context;
	private String methodName;

	public CheckboxPanel(String label, Object context,
			String methodName) {
		
		this.context = context;
		this.methodName = methodName;
		
		setBorder(BorderFactory.createLineBorder(Color.black));
	    JCheckBox c = new JCheckBox(label);
	    add(c);
	    c.setSelected(true);
	    c.addItemListener(this);
	}

	@Override
	public void itemStateChanged(ItemEvent e) {
	    	
    	try {
	    		
    		Class<?>[] params = {boolean.class};
			Method setMethod = context.getClass().getMethod("set".concat(methodName), params);
			if(e.getStateChange()==ItemEvent.DESELECTED)
				setMethod.invoke(context,false);
			else setMethod.invoke(context,true);
			
		} catch (SecurityException e1) {
			e1.printStackTrace();
		} catch (NoSuchMethodException e1) {
			e1.printStackTrace();
		}catch (IllegalArgumentException e1) {
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		} catch (InvocationTargetException e1) {
			e1.printStackTrace();
		}
	}	
}